package com.fzz.netty.study.test;

import com.sun.corba.se.internal.CosNaming.BootstrapServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author fankai
 * @version 1.0
 * @classname WebSocketServer
 * @description TODO
 * @date 2021/11/02 17:08
 **/

public class WebSocketServer {

    private String websocketPath = "/ws";
    private int port = 17002;


    public void start(){
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();

        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(boss,work)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    //http 编解码器
                                    .addLast(new HttpServerCodec())
                                    //聚合内容的最大长度，以字节为单位
                                    .addLast(new HttpObjectAggregator(65536))
                                    //以块写，解决大数据问题
                                    .addLast(new ChunkedWriteHandler())
                                    //日志等级
                                    .addLast(new LoggingHandler(LogLevel.DEBUG))
                                    //path 连接路径
                                    .addLast(new WebSocketServerProtocolHandler(websocketPath))
                                    .addLast(new WebSocketFrameHandler());
                        }
                    });

            final ChannelFuture channelFuture = sb.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

}
